package org.way.file.util;

import com.deepoove.poi.XWPFTemplate;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.config.ConfigureBuilder;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;
import org.way.base.util.ServletUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Map;

@Slf4j
@Component
public class PoiUtil {

    /**
     * 读取resource目录下的文件
     */
    public static void readResourceFiles() throws IOException {
        Resource[] resources = new PathMatchingResourcePatternResolver()
                .getResources("classpath*:word/template.docx");
        for (Resource resource : resources) {
            File file = new File(resource.getURL().getFile());
            String path = file.getPath();
            log.info(path);
        }
    }

    public static void downLoad(String filePath, String realFileName) {
        String percentEncodedFileName;
        try {
            percentEncodedFileName = percentEncode(realFileName);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        final HttpServletResponse response = getHttpServletResponse(percentEncodedFileName);
        try (BufferedInputStream bis = new BufferedInputStream(Files.newInputStream(Paths.get(filePath)));
             BufferedOutputStream bos = new BufferedOutputStream(response.getOutputStream());) {
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = bis.read(buff)) > 0) {
                bos.write(buff, 0, len);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 百分号编码工具方法
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }

    public static HttpServletResponse getHttpServletResponse(String percentEncodedFileName) {
        String contentDispositionValue = "attachment; filename=" + percentEncodedFileName + ";" + "filename*=" + "utf-8''" + percentEncodedFileName;

        HttpServletResponse response = ServletUtils.getResponse();
        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", contentDispositionValue);
        response.setHeader("download-filename", percentEncodedFileName);
        return response;
    }

    public void exportWord(String tempTemplateFilePath, String fileName, Map<String,Object> data, String... listKeys) {
        String tmpPath = "D:\\" + fileName;
        try {
            LoopRowTableRenderPolicy hackLoopTableRenderPolicy = new LoopRowTableRenderPolicy();
            ConfigureBuilder builder = Configure.builder();
            builder.bind(hackLoopTableRenderPolicy,listKeys);
            Configure config = builder.build();
            XWPFTemplate template = XWPFTemplate.compile(tempTemplateFilePath, config).render(data);
            FileOutputStream fos = new FileOutputStream(tmpPath);
            template.write(fos);
            fos.flush();
            fos.close();
            template.close();
            PoiUtil.downLoad(tmpPath, fileName);
        } catch (Exception e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException("导出文件失败");
        } finally {
            log.info(tmpPath);
            log.info(tempTemplateFilePath);
            File file = new File(tmpPath);
            file.delete();
            File copyFile = new File(tempTemplateFilePath);
            copyFile.delete();
        }
    }

    /**
     * 将项目中的模板文件拷贝到根目录下
     */
    public String copyTempFile(String templeFilePath) {
        InputStream inputStream = getClass().getClassLoader().getResourceAsStream(templeFilePath);
        String tempFileName = System.getProperty("user.home") + "/" + "temp.docx";
        File tempFile = new File(tempFileName);
        try {
            assert inputStream != null;
            FileUtils.copyInputStreamToFile(inputStream, tempFile);
        } catch (IOException e) {
            log.error(e.getMessage(),e);
            throw new RuntimeException("导出文件失败");
        }
        return tempFile.getPath();
    }
}
